<?php


namespace app\service;


class Jwt
{


    private $header;

    private $secret;

    private $error;

    private $payload;

    public function __construct($payload = [])
    {
        $this->header = config('jwt.header') ?? [
                'alg' => 'HS256', //生成signature的算法
                'typ' => 'JWT'    //类型
            ];

        $this->secret = config('jwt.secret') ?? '123456';

        $this->payload = $payload;
    }

    /**
     * 获取jwt token
     *
     * @param int $uid
     * @return bool|string
     */
    public function token(int $uid)
    {
        $jwt = config('jwt');
        $payload = [
            'iss' => $jwt['iss'] ?? 'web',
            'uid' => $uid,
            'iat' => time(),
            'exp' => time() + $jwt['exp'] ?? 3600,
            'nbf' => time(),
            'sub' => $jwt['sub'] ?? '',
            'jti' => md5(uniqid('JWT') . time())
        ];

        $payload = array_merge($payload,$this->payload);

        if (is_array($payload)) {
            $base64header = $this->base64UrlEncode(json_encode($this->header, JSON_UNESCAPED_UNICODE));
            $base64payload = $this->base64UrlEncode(json_encode($payload, JSON_UNESCAPED_UNICODE));
            return $base64header . '.' . $base64payload . '.' . $this->signature($base64header . '.' . $base64payload, $this->secret, $this->header['alg']);
        } else {
            return false;
        }
    }


    /**
     * 验证token是否有效,默认验证exp,nbf,iat时间
     * @param string $Token 需要验证的token
     * @return bool|string
     */
    public function verifyToken(string $Token)
    {
        $tokens = explode('.', $Token);
        if (count($tokens) != 3)
        {
            $this->setError('The token is not yet valid.');
            return false;
        }

        list($base64header, $base64payload, $sign) = $tokens;

        //获取jwt算法
        $base64decodeheader = json_decode($this->base64UrlDecode($base64header), JSON_OBJECT_AS_ARRAY);
        if (empty($base64decodeheader['alg'])) {
            $this->setError('The token is not yet valid.');
            return false;
        }

        //签名验证
        if ($this->signature($base64header . '.' . $base64payload, $this->secret, $base64decodeheader['alg']) !== $sign) {
            $this->setError('The token is not yet valid.');
            return false;
        }

        $payload = json_decode($this->base64UrlDecode($base64payload), JSON_OBJECT_AS_ARRAY);

        //签发时间大于当前服务器时间验证失败
        if (isset($payload['iat']) && $payload['iat'] > time()) {
            $this->setError('The token is not yet valid (iat).');
            return false;
        }

        //过期时间小宇当前服务器时间验证失败
        if (isset($payload['exp']) && $payload['exp'] < time()) {
            $this->setError('The token is not yet valid (exp).');
            return false;
        }

        //该nbf时间之前不接收处理该Token
        if (isset($payload['nbf']) && $payload['nbf'] > time()) {
            $this->setError('The token is not yet valid (nbf).');
            return false;
        }

        return $payload;
    }


    /**
     * base64UrlEncode   https://jwt.io/  中base64UrlEncode编码实现
     * @param string $input 需要编码的字符串
     * @return string
     */
    private function base64UrlEncode(string $input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    /**
     * base64UrlEncode  https://jwt.io/  中base64UrlEncode解码实现
     * @param string $input 需要解码的字符串
     * @return bool|string
     */
    private function base64UrlDecode(string $input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addlen = 4 - $remainder;
            $input .= str_repeat('=', $addlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

    /**
     * HMACSHA256签名   https://jwt.io/  中HMACSHA256签名实现
     * @param string $input 为base64UrlEncode(header).".".base64UrlEncode(payload)
     * @param string $secret
     * @param string $alg 算法方式
     * @return mixed
     */
    private function signature(string $input, string $secret, string $alg = 'HS256')
    {
        $alg_config = array(
            'HS256' => 'sha256'
        );
        return $this->base64UrlEncode(hash_hmac($alg_config[$alg], $input, $secret, true));
    }

    /**
     * @return mixed
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * @param mixed $error
     */
    public function setError($error): void
    {
        $this->error = $error;
    }
}
